﻿using System.Collections.Generic;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using SoftSource.Common;
using SoftSource.Common.Converters;

namespace SoftSource.Controls
{
    public sealed class EnumComboBox : ComboBox
    {
        private static EnumToDisplayNamePairConverter pairConverter;
        private static EnumToDisplayNamePairCollectionConverter collectionConverter;

        public EnumComboBox()
        {
            this.DefaultStyleKey = typeof(EnumComboBox);

            this.DisplayMemberPath = "Value";

            if (pairConverter == null)
                pairConverter = new EnumToDisplayNamePairConverter();

            if (collectionConverter == null)
                collectionConverter = new EnumToDisplayNamePairCollectionConverter();

            this.DataContext = this;

            Binding itemsSourceBinding = new Binding("Enumeration");
            itemsSourceBinding.Converter = EnumComboBox.collectionConverter;
            itemsSourceBinding.Mode = BindingMode.OneTime;

            Binding selectedItemBinding = new Binding("Enumeration");
            selectedItemBinding.Converter = EnumComboBox.pairConverter;
            selectedItemBinding.Mode = BindingMode.TwoWay;

            this.SetBinding(EnumComboBox.ItemsSourceProperty, itemsSourceBinding);
            this.SetBinding(EnumComboBox.SelectedItemProperty, selectedItemBinding);
        }

        public object Enumeration
        {
            get { return (object)GetValue(EnumerationProperty); }
            set { SetValue(EnumerationProperty, value); }
        }

        // Using a DependencyProperty as the backing store for Enumeration.  This enables animation, styling, binding, etc...
        public static readonly DependencyProperty EnumerationProperty =
            DependencyProperty.Register("Enumeration", typeof(object), typeof(EnumComboBox), new PropertyMetadata(null, (sender, e) =>
                {
                    EnumComboBox cb = sender as EnumComboBox;
                    if (cb != null)
                        cb.ItemsSource = EnumComboBox.collectionConverter.Convert<Dictionary<object, string>>(e.NewValue);
                }));
    }
}
